/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package controller.admin;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import model.League;
import model.LeagueService;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import view.admin.forms.AddLeagueStrutsActionForm;

/**
 *
 * @author Thai Dac Vinh
 */
public class AddLeagueStrutsAction extends org.apache.struts.action.Action {

    /* forward name="success" path="" */
    private static final String SUCCESS = "success";

    /**
     * This is the action called from the Struts framework.
     *
     * @param mapping The ActionMapping used to select this instance.
     * @param form The optional ActionForm bean for this request.
     * @param request The HTTP Request we are processing.
     * @param response The HTTP Response we are processing.
     * @throws java.lang.Exception
     * @return
     */
    @Override
    public ActionForward execute(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        // Use Struts actions to record business processing errors.
        ActionErrors errors = new ActionErrors();
        // Store this set in the request scope, in case we need to send the ErrorPage view.
        saveErrors(request, errors);
        try {
            AddLeagueStrutsActionForm add_league_form = (AddLeagueStrutsActionForm) form;
            
            ServletContext context = this.getServlet().getServletContext();
            LeagueService league_service = (LeagueService) context.getAttribute("leagueService");
            
            League league = league_service.addLeague(add_league_form.getYear(), add_league_form.getSeason(), add_league_form.getTitle());
            if (league == null) {
                System.err.println("Can not add league");
            } else {
                request.setAttribute("league", league);
                return mapping.findForward(SUCCESS);
            }
        } catch(Exception e) {
            System.err.println(e);
        }
        return mapping.findForward("error");
    }
}
